
import React, { useEffect, useState, useCallback, useRef } from 'react';
import CommonService from '../../../../app/services/commonService';
import UniversityService from '../../../../app/services/universityService';
import { MagnifyingGlassIcon } from '@heroicons/react/20/solid';
import UnivFilters from "../../../../app/const/const";
import UniverseityMajorItem from '../universeityMajorItem';

import _ from 'lodash';

const UniversityMajorView = ({ universityId, relationId, sortIndex,addMajorToClonedSheet }) => {

    const [data, setData] = useState([]);
    const [total, setTotal] = useState(0);
   

    const pageIndexArray = useRef([]);
    const collapseItemRef = useRef(null);
    var loading = false;



    const [queryParams, setQueryParams] = useState({
        pageIndex: 1,
        pageSize: 10,
        universityName: '',
        startScore: '',
        endScore: '',
        startRank: '',
        endRank: '',
        category: '',
        attr: '',
        type: '',
        relationId: relationId,
        province: '',
    });

    const divRef = useRef(null);
    const fetchData = useCallback(() => {
        loadData()
    }, [universityId, sortIndex, queryParams.pageIndex]);

    useEffect(() => {
        fetchData()
    }, [universityId, sortIndex, queryParams.pageIndex])

    const loadData = async () => {
        if (_.includes(pageIndexArray.current, queryParams.pageIndex) && universityId === null) {
            return;
        }
        loading = true
        CommonService.setLoading(true);
        UniversityService.universityEnrollInfos({...queryParams,universityId:universityId}).then((res) => {
            // divRef.current.scrollTo({ top: 0, behavior: 'smooth' });
            if (res.success) {
                const currentData = queryParams.pageIndex == 1 ? res.data : data.concat(res.data);
                setData(currentData);
                setTotal(res.total);
                pageIndexArray.current.push(queryParams.pageIndex);
                if(universityId !== null && universityId > 0){
                    setQueryParams({
                        pageIndex: 1,
                        pageSize: 10,
                        universityName: '',
                        startScore: '',
                        endScore: '',
                        startRank: '',
                        endRank: '',
                        category: '',
                        attr: '',
                        type: '',
                        relationId: relationId,
                        province: '',
                    })
                }
            }
        }).finally(() => {
            CommonService.setLoading(false);
            loading = false
        })
    }

    const reset = () => {
        setQueryParams({
            pageIndex: 1,
            pageSize: 10,
            universityName: '',
            startScore: '',
            endScore: '',
            startRank: '',
            endRank: '',
            category: '',
            attr: '',
            type: '',
            relationId: relationId,
            province: '',
        });
        pageIndexArray.current = [];
        loadData();
        collapseItemRef.current.click();
    }

    const changeQueryParams = (key, e) => {
        const itemStr = `{ "${key}" : "${e.target.value}" }`
        const item = JSON.parse(itemStr)
        setQueryParams({ ...queryParams, ...item, pageIndex: 1 });
    }

    const onSearchingData = () => {
        pageIndexArray.current = [];
        if (queryParams.pageIndex === 1) {
            loadData();
        } else {
            setQueryParams({ ...queryParams, pageIndex: 1 });
        }
        collapseItemRef.current.click();
        
    }

    const onScrollHandler = () => {
        if (divRef.current.scrollTop + divRef.current.clientHeight + 200 >= divRef.current.scrollHeight && ( universityId === null || universityId === 0)) {
            if (data.length < total) {
                if (!loading) {
                    setQueryParams({ ...queryParams, pageIndex: queryParams.pageIndex + 1 });
                }
            }
        }
    }

    return (
        <>
            <div className="container text-xs" >
                <div className='w-full overflow-hidden' style={{height:'630px'}}>
                    <div className='flex flex-col'>
                        {(universityId == null || universityId === 0) && <div className="w-full p-4 card  bg-base-100">
                            <div tabIndex={0} className="collapse  collapse-arrow border border-base-300 bg-base-200 " ref={collapseItemRef}>
                                <input type="checkbox" />
                                <div className="collapse-title text-base font-medium">
                                    查询条件
                                </div>
                                <div className="collapse-content">
                                    <div className="flex flex-col ">
                                        <div className="flex flex-row items-baseline justify-start my-1">
                                            <div className="flex flex-row items-baseline justify-start mx-2">
                                                <div className="text-xs font-semibold">院校名称</div>
                                                <input type="text" className="input input-bordered w-60  mx-2 input-sm " value={queryParams.universityName} onChange={(e) => changeQueryParams('universityName', e)} />
                                            </div>
                                            <div className="flex flex-row items-baseline justify-start mx-2">
                                                <div className="text-xs font-semibold">开始分数</div>
                                                <input type="number" className="input input-bordered w-60  mx-2 input-sm " value={queryParams.startScore} onChange={(e) => changeQueryParams('startScore', e)} />
                                            </div>
                                            <div className="flex flex-row items-baseline justify-start mx-2">
                                                <div className="text-xs font-semibold">结束分数</div>
                                                <input type="number" className="input input-bordered w-60  mx-2 input-sm " value={queryParams.endScore} onChange={(e) => changeQueryParams('endScore', e)} />
                                            </div>
                                        </div>
                                        <div className="flex flex-row items-baseline justify-start my-1">
                                            <div className="flex flex-row items-baseline justify-start mx-2">
                                                <div className="text-xs font-semibold">开始位次</div>
                                                <input type="number" className="input input-bordered w-60  mx-2 input-sm " value={queryParams.startRank} onChange={(e) => changeQueryParams('startRank', e)} />
                                            </div>
                                            <div className="flex flex-row items-baseline justify-start mx-2">
                                                <div className="text-xs font-semibold">结束位次</div>
                                                <input type="number" className="input input-bordered w-60  mx-2 input-sm " value={queryParams.endRank} onChange={(e) => changeQueryParams('endRank', e)} />
                                            </div>
                                            <div className="flex flex-row items-baseline justify-start mx-2" >
                                                <div className="text-xs font-semibold">院校分类</div>
                                                <select className="select select-bordered w-60 mx-2  select-sm" value={queryParams.category} onChange={(e) => changeQueryParams('category', e)}>
                                                    <option value='' >全部</option>
                                                    {UnivFilters.UniversityCategory.map((item, index) => {
                                                        return <option key={index} value={item} >{item}</option>
                                                    })
                                                    }
                                                </select>
                                            </div>
                                        </div>
                                        <div className="flex flex-row items-baseline justify-start my-1">
                                            <div className="flex flex-row items-baseline justify-start mx-2" >
                                                <div className="text-xs font-semibold">办学类型</div>
                                                <select className="select select-bordered w-60 mx-2  select-sm" value={queryParams.type} onChange={(e) => changeQueryParams('type', e)}>
                                                    <option value='' >全部</option>
                                                    {UnivFilters.UniversityType.map((item, index) => {
                                                        return <option key={index} value={item} >{item}</option>
                                                    })
                                                    }
                                                </select>
                                            </div>
                                            <div className="flex flex-row items-baseline justify-start mx-2" >
                                                <div className="text-xs font-semibold">院校属性</div>
                                                <select className="select select-bordered w-60 mx-2  select-sm" value={queryParams.attr} onChange={(e) => changeQueryParams('attr', e)}>
                                                    <option value='' >全部</option>
                                                    {UnivFilters.UniversityAttr.map((item, index) => {
                                                        return <option key={index} value={item} >{item}</option>
                                                    })
                                                    }
                                                </select>
                                            </div>
                                            <div className="flex flex-row items-baseline justify-start mx-2" >
                                                <div className="text-xs font-semibold">院校区域</div>
                                                <select className="select select-bordered w-60 mx-2  select-sm" value={queryParams.province} onChange={(e) => changeQueryParams('province', e)}>
                                                    <option value='' >全部</option>
                                                    {UnivFilters.ProvinceItems.map((item, index) => {
                                                        return <option key={index} value={item} >{item}</option>
                                                    })
                                                    }
                                                </select>
                                            </div>
                                        </div>
                                        <div className="flex flex-row items-baseline justify-between my-1">

                                            <div className="flex flex-row items-baseline justify-start mx-2">
                                                <button className="btn btn-sm bg-secondary text-white" onClick={reset}><MagnifyingGlassIcon className="w-4 h-4" />重置</button>
                                                <button className="btn btn-sm bg-primary text-white" onClick={onSearchingData}><MagnifyingGlassIcon className="w-4 h-4" />查询</button>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div> }
                    </div>
                    <div className='flex flex-col w-full overflow-y-auto'
                        ref={divRef}
                        onScrollCapture={() => onScrollHandler()}
                        style={{ height: '540px' }}>
                        {
                            data && data.length > 0 && data.map((item, index) => {
                                return <div key={index}> <UniverseityMajorItem data={item} addMajorToClonedSheet={(scoreItem)=>addMajorToClonedSheet(scoreItem)}/></div>
                            })
                        }
                    </div>
                </div>
            </div>
        </>
    )
}

export default UniversityMajorView;